<?php

namespace app\helper;

use app\atrait\Single;
use Exception;
use support\Cache;
use support\Redis;

class Config
{

    use Single;


    protected string $keyPrefix;


    public function __construct()
    {
        $this->keyPrefix = 'CONFIG:';
    }


    /**
     * 新建键名
     *
     * @param $key
     * @param $value
     * @param string $desc
     * @param int $ttl
     * @return bool
     * @throws Exception
     */
    public function Set($key, $value, string $desc = '', int $ttl = 0): bool
    {

        try {
            $isExists = \app\model\Config::where('key', $key)->exists();
            if (!$isExists) {
                \app\model\Config::create([
                    'key' => $key,
                    'value' => $value ?? '',
                    'desc' => $desc,
                    'expires_in' => $ttl,
                ]);
            } else {
                \app\model\Config::where('key', $key)->update([
                    'value' => $value ?? '',
                    'expires_in' => $ttl,
                ]);
            }

            if (empty($ttl)) {
                Cache::set($this->keyPrefix . $key, $value);
            } else {
                Cache::set($this->keyPrefix . $key, $value, $ttl);
            }
        } catch (Exception) {
            throw new Exception('配置项添加失败', 500);
        }

        return true;

    }


    /**
     * 获取键值
     *
     * @param $key
     * @param string $default
     * @return mixed
     */
    public function Get($key, string $default = ''): mixed
    {

        $prefix = getenv('REDIS_PREFIX') . getenv('CACHE_PREFIX');

//        return Cache::get($this->keyPrefix . $key, $default);
        $data = Redis::get($prefix . ':' . $this->keyPrefix . $key);
        try {
            return unserialize($data);
        } catch (Exception) {
            return $data;
        }

    }
}
